package com.bianmaba.beans.datamanagement;

import com.bianmaba.spring.data.jpa.domain.annotations.QueryCacheable;
import com.bianmaba.spring.data.jpa.domain.entity.UuidIdentityEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.struts2.json.annotations.JSON;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@DynamicUpdate()
@DynamicInsert()
//此注解重新定义为是否开始查询缓存
@QueryCacheable
//此注解表示此类支持二级缓存，缓存名称为：defaultEntityCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Data
@NoArgsConstructor
public class DataRow extends UuidIdentityEntity {
    //数据开始时间
    @Column(columnDefinition = "date")
    private Date startDate;
    //数据结束时间
    @Column(columnDefinition = "date")
    private Date endDate;


    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "data_row_ref_data_item", joinColumns = {@JoinColumn(name = "data_row_id")}, inverseJoinColumns = {@JoinColumn(name = "data_item_id")})
    private List<DataItem> dataItems = new ArrayList<>();

    @JSON(format = "yyyy-MM-dd")
    public Date getStartDate() {
        return this.startDate;
    }

    @JSON(format = "yyyy-MM-dd")
    public Date getEndDate() {
        return this.endDate;
    }

    public static DataRow of(List<DataItem> items) {
        DataRow row = new DataRow();
        row.dataItems = items;
        return row;
    }

    public static DataRow of(Date startDate, Date endDate, List<DataItem> items) {
        DataRow row = new DataRow();
        row.startDate = startDate;
        row.endDate = endDate;
        row.dataItems = items;
        return row;
    }

    public String getValue(String propertyName) {
        for (DataItem item : this.dataItems) {
            if (item.getProperty().equalsIgnoreCase(propertyName)) {
                return item.getValue();
            }
        }
        return null;
    }
}
